<?php

namespace app\middleware;

use app\service\JwtService;
use ReflectionClass;
use support\Log;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class JwtAuth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 从Authorization header中获取token
        $authHeader = $request->header('Authorization', '');

        //如果header中有Authorization头，则检查是否以Bearer开头，以Bearer开头的话则获取token并验证
        if (strpos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7); // 移除 'Bearer ' 前缀
            try {
                // 验证JWT token
                $decoded = JwtService::verifyToken($token);
                if ($decoded == false) {
                    return new Response(401, [], json_encode(['error' => 'token verification failed']));
                }
                // 将用户信息存储在request中供后续使用
                $request->currUser = $decoded;
                // 继续处理请求
                return $handler($request);
            } catch (\Exception $e) {
                // Token验证失败
                return new Response(401, [], json_encode(['error' => $e->getMessage()]));
            }
        }

        //如果没有Authorization头，则检查是否在noNeedLogin数组中，如果在则继续处理请求，否则拦截请求并返回一个重定向响应
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];
        // Log::debug("noNeedLogin", $noNeedLogin);
        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            // 拦截请求，返回一个重定向响应，请求停止向洋葱芯穿越
            return redirect('#/login');
        }
        // 不需要登录，请求继续向洋葱芯穿越
        return $handler($request);
    }
}
